'use strict';

/**
 * 用户角色关联模型
 * @param app
 */
module.exports = app => {
  const { INTEGER, STRING, DATE, BIGINT } = app.Sequelize;

  const UserRole = app.model.define('sys_user_roles', {
    id: {
      type: BIGINT,
      primaryKey: true,
      comment: '关联ID',
    },
    userId: {
      type: BIGINT,
      allowNull: false,
      comment: '用户ID',
      field: 'user_id',
    },
    roleCode: {
      type: STRING(50),
      allowNull: false,
      comment: '角色编码',
      field: 'role_code',
    },
    createTime: {
      type: DATE,
      allowNull: false,
      comment: '创建时间',
      field: 'create_time',
      defaultValue: app.Sequelize.NOW,
    },
    updateTime: {
      type: DATE,
      allowNull: false,
      comment: '更新时间',
      field: 'update_time',
      defaultValue: app.Sequelize.NOW,
    },
  });

  // 在创建前生成雪花ID
  UserRole.beforeCreate((userRole, options) => {
    const { generateSnowflakeId } = require('../utils/snowflake');
    userRole.id = generateSnowflakeId();
  });

  // 自定义toJSON方法，避免字段重复
  UserRole.prototype.toJSON = function() {
    const values = Object.assign({}, this.get());
    // 移除重复的下划线字段
    delete values.create_time;
    delete values.update_time;
    return values;
  };

  // 关联关系
  UserRole.associate = function() {
    // 关联用户
    app.model.UserRole.belongsTo(app.model.User, {
      foreignKey: 'user_id',
      as: 'user',
    });
    // 关联角色
    app.model.UserRole.belongsTo(app.model.Role, {
      foreignKey: 'role_code',
      targetKey: 'code', // 指定Role模型的目标键为code
      as: 'role',
    });
  };

  return UserRole;
};
